# OrderLogic Test Frame

symbol <- "AAPL"
symname <- paste(symbol, ".vadb", sep="")
entry <- "o1"
direction <- "long"
LL <- 0.75
WL <- 2
fromtodates<-c("1998-01-01", "")

getSymbols(symbol, src="vadb")
OHLC <- get(symname)
myOrderXTS <- CSPDarkCloudCover(OHLC)[,1] & TrendDetectionChannel(lag(OHLC, k=1))[,"DownTrend"]
subsetstring <- paste(fromtodates[1], "/", sep="")       # ensure that TS and myOrderXTS have same indexes
myOrderXTS <- myOrderXTS[subsetstring]

if (entry=="c0") {
  EntryPrice <- Cl(get(symname))
} else if (entry=="o1") {
  EntryPrice <- as.xts(Next(Op(get(symname))))
} else if (entry=="c1") {
  EntryPrice <- as.xts(Next(Cl(get(symname))))
}
EntryPrice <- EntryPrice[subsetstring]
XATR <- ATR(cbind(Hi(OHLC), Lo(OHLC), Cl(OHLC)))[subsetstring]
if (direction=="long") {
  OrderTS <- merge(myOrderXTS, 0, 
                   (LL>0) * EntryPrice-LL*XATR[,'atr'], 
                   (WL>0) * EntryPrice+WL*XATR[,'atr'])
  colnames(OrderTS) <- c("long", "short", "stoploss", "stopwin")
} else if (direction=="short") {
  OrderTS <- merge(myOrderXTS, 0,
                   (LL>0) * EntryPrice+LL*XATR[,'atr'], 
                   (WL>0) * EntryPrice-WL*XATR[,'atr'])
  colnames(OrderTS) <- c("short", "long", "stoploss", "stopwin")
}

comb <- (cbind(OHLC, XATR, OrderTS))

OL <- orderLogic(OHLC[subsetstring], OrderTS, n=10, entry="o1")



ROC1 <- function (OrderTS) {
  Trade <- OrderTS[,"long"] | OrderTS[,"short"]
  Filtered <- OrderTS[Trade]
  ret <- Filtered[,"closeprice"]/Filtered[,"openprice"] - 1
  colnames(ret) <- "return"
  return (ret)
}